﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using Spire.Doc;

namespace PdfOperator
{
    public partial class FrmWordToPdf : Form
    {
        public FrmWordToPdf()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择待转换文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFiles = new OpenFileDialog();
            openFiles.Multiselect = true;
            openFiles.Filter = "word文档|*.docx;*.doc";
            if (openFiles.ShowDialog() == DialogResult.OK)
            {
                string[] filenames = openFiles.FileNames;
                Array.Sort(filenames);
                foreach (string filename in filenames)
                {
                    lstBoxFileList.Items.Add(filename);
                }
            }
        }

        /// <summary>
        /// 选择保存路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSavePath_Click(object sender, EventArgs e)
        {
            if (lstBoxFileList.Items.Count < 1)
            {
                MessageBox.Show("请添加要转换的word文档！");
                return;
            }
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                txtSavePath.Text = folderBrowser.SelectedPath;
            }
        }

        /// <summary>
        /// 开始word转PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartCsharp_Click(object sender, EventArgs e)
        {
            if (lstBoxFileList.Items.Count < 1)
            {
                MessageBox.Show("请添加要操作的word文档！");
                return;
            }
            //if (string.IsNullOrEmpty(txtSavePath.Text))
            //{
            //    MessageBox.Show("请选择文件保存路径！");
            //    return;
            //}

            foreach (var item in lstBoxFileList.Items)
            {
                string fileName = item.ToString();
                Document document = new Document();
                document.LoadFromFile(fileName);
                string outputFileName = $"{Path.GetFileNameWithoutExtension(fileName)}.pdf";
                document.SaveToFile(Path.Combine(Path.GetDirectoryName(fileName), outputFileName), FileFormat.PDF);
            }

            MessageBox.Show("完成！");
        }

        /// <summary>
        /// 开始word转PDF(python)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartPy_Click(object sender, EventArgs e)
        {
            if (lstBoxFileList.Items.Count < 1)
            {
                MessageBox.Show("请添加要操作的word文档！");
                return;
            }
            //if (string.IsNullOrEmpty(txtSavePath.Text))
            //{
            //    MessageBox.Show("请选择文件保存路径！");
            //    return;
            //}
            if (!File.Exists("WordToPdf.exe"))   //文件不存在
            {
                MessageBox.Show("文件缺失，请检查！");
                return;
            }

            string args = "";
            for (int i = 0; i < lstBoxFileList.Items.Count; i++)
            {
                string wordfileName = lstBoxFileList.Items[i].ToString();
                args = args + wordfileName + " ";
            }
            args = args.Trim();

            try
            {
                Process myProcess = new Process();
                // 调用当前目录下的WordToPdf.exe（Python程序）进行转换
                ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("WordToPdf.exe", args);
                myProcessStartInfo.CreateNoWindow = true;
                myProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                myProcess.StartInfo = myProcessStartInfo;
                myProcess.Start();

                while (!myProcess.HasExited)
                {
                    myProcess.WaitForExit();
                }

                _ = myProcess.ExitCode;
                myProcess.Dispose();
                myProcess.Close();

                MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnOpenSaveFolder_Click(object sender, EventArgs e)
        {
            //判断文件是否存在
            if (!Directory.Exists(txtSavePath.Text))
            {
                return;
            }
            else
            {
                //存在文件夹
                Process.Start("explorer.exe", txtSavePath.Text);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 开始拖放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstBoxFileList_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
                this.lstBoxFileList.Cursor = Cursors.Arrow; //指定鼠标形状   
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 接收拖放文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstBoxFileList_DragDrop(object sender, DragEventArgs e)
        {
            var paths = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetEnumerator();
            while (paths.MoveNext())
            {
                string file = paths.Current.ToString();
                string ext = Path.GetExtension(file).ToLower();
                if (ext == ".doc" || ext == "docx")
                {
                    lstBoxFileList.Items.Add(file);
                }
            }

            this.lstBoxFileList.Cursor = Cursors.Default; //还原鼠标形状 
        }

        /// <summary>
        /// delete键删除列表选中项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstBoxFileList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                lstBoxFileList.Items.Remove(lstBoxFileList.SelectedItem);
            }
        }


    }
}
